import { ref } from 'vue'
import { defineStore } from 'pinia'
import storage from '@/utils/storage'
import setting from '@/config/setting'

const storageToken = storage.get(setting.tokenStoreName, false)
export const useUserStore = defineStore('user', () => {
  const user = ref(false)
  const token = ref(storageToken)
  const authorities = ref([])

  const setUserToken = (value) => {
    if (value) {
      token.value = value
      storage.set(setting.tokenStoreName, value)
    } else {
      token.value = ''
      storage.remove(setting.tokenStoreName)
    }
  }

  const setUserInfo = (info) => {
    user.value = {
      IsSuper: info.IsSuper,
      NickName: info.NickName,
      UserID: info.UserID,
      UserName: info.UserName,
      UserStatus: info.UserStatus
    }

    let power = []
    info.authorities.forEach(item => {
      power.push(item.authority)
    })
    authorities.value = power
  }

  const loginOut = () => {
    user.value = {}
    token.value = false
    authorities.value = []
    storage.remove(setting.tokenStoreName)
  }

  return {
    user,
    token,
    authorities,
    setUserToken,
    setUserInfo,
    loginOut
  }
})
